package com.lagou.edu.controller;

import com.lagou.edu.service.CodeServiceFeignClient;
import com.lagou.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@RestController
@RequestMapping("/user")
//@RefreshScope
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private CodeServiceFeignClient codeServiceFeignClient;


    @GetMapping("/login/{email}/{password}")
    public String login(HttpServletResponse response, HttpSession session,
                        @PathVariable String email, @PathVariable String password){
        String mail = userService.login(email, password);
        if("false".equals(mail)){
            return mail;
        }
//        session.setAttribute("email",mail);
        UUID uuid = UUID.randomUUID();
        userService.saveToken(email,uuid.toString());
        saveCookie(response, uuid.toString());

        return mail;
    }

    @GetMapping("/register/{email}/{password}/{code}")
    public int register(@PathVariable String email, @PathVariable String password,
                            @PathVariable String code, HttpServletResponse response){
        // true是已经注册
        boolean register = userService.isRegister(email);
        if(register){
            return 3;
        }
        // 校验验证码是否正确，0正确1错误2超时
        int validate = codeServiceFeignClient.validate(email, code);
        if(validate > 0){
            return validate;
        }
        boolean register1 = userService.register(email, password, code);
        if(register1){
//            saveCookie(response);
            return 0;
        }
        return 6;
    }

    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable String email){
        return userService.isRegister(email);
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable String token){
        return userService.getEmail(token);
    }

    public void saveCookie(HttpServletResponse response, String token){
        // 将token保存到cookie中
        Cookie cookie = new Cookie("token",token);
        cookie.setPath("/");
        cookie.setDomain("www.test.com");
        response.addCookie(cookie);
    }
}
